package com.googlecode.flealancemarket.tapestry.pages.inbox;

import com.googlecode.flealancemarket.core.tapestry.SpringBean;
import com.googlecode.flealancemarket.metamodel.PrivateMessage;
import com.googlecode.flealancemarket.service.commands.CountReceivedMessagesForUser;
import com.googlecode.flealancemarket.service.commands.GetReceivedMessagesForUser;
import com.googlecode.flealancemarket.service.commands.ChangeMessageRead;
import com.googlecode.flealancemarket.service.commands.DeleteMessage;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.List;
import org.apache.tapestry.annotations.OnEvent;
import org.apache.tapestry.ioc.annotations.Inject;

public class Index extends AbstractMessagesPage {

    @Inject
    @SpringBean("com.googlecode.flealancemarket.service.commands.CountReceivedMessagesForUser")
    private CountReceivedMessagesForUser countReceivedMessagesForUser;

    @Inject
    @SpringBean("com.googlecode.flealancemarket.service.commands.GetReceivedMessagesForUser")
    private GetReceivedMessagesForUser getReceivedMessagesForUser;

    @Inject
    @SpringBean("com.googlecode.flealancemarket.service.commands.ChangeMessageRead")
    private ChangeMessageRead changeMessageRead;

    public int calculateMessagesNumber() {
        countReceivedMessagesForUser.setUser(getUser());
        return countReceivedMessagesForUser.execute();
    }

    public List<PrivateMessage> receiveMessagesList(){
        getReceivedMessagesForUser.setPage(getPageNumber());
        getReceivedMessagesForUser.setUser(getUser());
        return getReceivedMessagesForUser.execute();
    }

    @OnEvent(component="toggleRead")
    void toggleRead(Long id){
        for(PrivateMessage temp : getMessages()){
            if(temp.get_id().equals(id)){
                changeMessageRead.setMessage(temp);
                changeMessageRead.setRead(!temp.getRead());
                break;
            }
        }
        changeMessageRead.execute();
    }

    public boolean messageRead(){
        return getMessage().getRead();
    }
}
